package org.dev.hi.hiui.banner.core;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import java.lang.reflect.Field;

public
/**
 * Author WenPing 
 * CreateTime 2021/4/13.
 * Description:
 * 实现自动翻页的ViewPager
 */

class HiViewPager extends ViewPager {

    private int mIntervalTime;

    private boolean mAutoPlay = true;

    private boolean isLayout;

    private Handler mHandler = new Handler();

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            //handler把当前的runnable对象添加到handler的队列中，
            // 该run方法会被对应的消息处理调用
            /**
             * 下面方法的逻辑是先调用next方法，然后延时一定时间调用handler的方法，实现反复调用的效果
             */
            next();
            mHandler.postDelayed(this, mIntervalTime);
        }
    };

    /**
     *
     */
    private int next() {
        int nextPosition = -1;

        if (getAdapter() == null || getAdapter().getCount() <= 1) {
            //adapter 不存在或者item的count数量不满足
            stop();
            return nextPosition;
        }

        nextPosition = getCurrentItem() + 1;
        //下一个索引大于adapter的view的最大数量时进行重置
        if (nextPosition >= getAdapter().getCount()) {
            nextPosition = ((HiBannerAdapter) getAdapter()).getFirstItemPosition();
        }
        //设置下一个index并滑动到对应的index的item
        setCurrentItem(nextPosition, true);
        return nextPosition;
    }

    /**
     * handler发送消息，实现循环滑页
     */
    public void start() {
        mHandler.removeCallbacksAndMessages(null);
        if (mAutoPlay) {
            mHandler.postDelayed(mRunnable, mIntervalTime);
        }
    }

    //把handler中的消息队列都移除
    private void stop() {
        mHandler.removeCallbacksAndMessages(null);
    }


    public HiViewPager(@NonNull Context context) {
        super(context);
    }

    public HiViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public void setAutoPlay(boolean autoPlay) {
        this.mAutoPlay = autoPlay;
        if (!mAutoPlay) {
            mHandler.removeCallbacks(mRunnable);
        }
    }

    public void setIntervalTime(int mIntervalTime) {
        this.mIntervalTime = mIntervalTime;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {

        //对比两个方法的差异；
        switch (ev.getActionMasked()) {
//        switch (ev.getActionMasked()) {
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                start();
                break;
            default:
                stop();
                break;
        }

        return super.onTouchEvent(ev);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        isLayout = true;
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (isLayout &&
                getAdapter() != null &&
                getAdapter().getCount() > 0) {
            //fix 使用RecyclerView + ViewPager bug https://blog.csdn.net/u011002668/article/details/72884893
            try {
                Field mScroller = ViewPager.class.getDeclaredField("mFirstLayout");
                mScroller.setAccessible(true);
                mScroller.set(this, false);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        //开始滑动咯
        start();
    }

    @Override
    protected void onDetachedFromWindow() {
        //修复 recyclerView 滑动，viewpager从被遮挡到重新显示时，item滑动异常的问题；
        if (((Activity) getContext()).isFinishing()) {
            super.onDetachedFromWindow();
        }
        //停止滑动咯
        stop();
    }

    public void setScrollDuration(int duration) {
        try {
            Field scrollerField = ViewPager.class.getDeclaredField("mScroller");
            scrollerField.setAccessible(true);
            //实现设置viewPager滑动的时间长短设置
            scrollerField.set(this,new HiBannerScroller(getContext(),duration));
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }

    }

}
